package top.hundreds.oasys.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import top.hundreds.common.crud.bean.PageParam;
import top.hundreds.common.crud.service.BaseService;
import top.hundreds.oasys.bean.converter.Converter;
import top.hundreds.oasys.bean.entity.Announcement;
import top.hundreds.oasys.bean.enums.AnnouncementStatus;
import top.hundreds.oasys.bean.enums.AnnouncementType;
import top.hundreds.oasys.bean.vo.AnnouncementVo;
import top.hundreds.oasys.mapper.AnnouncementMapper;
import top.hundreds.oasys.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (Announcement)表服务实现类
 *
 * @author lcf
 * @since 2021-01-29 19:12:52
 */
@Service("announcementService")
public class AnnouncementService extends BaseService<Announcement, AnnouncementMapper> {

    @Resource
    private Converter<Announcement,AnnouncementVo> announcementVoBuilder;

    @Resource
    private UserMapper userMapper;

    public void setStatus(Long id, Integer status) {
        if(AnnouncementStatus.formValue(status) == AnnouncementStatus.UNPUBLISHED) {
            this.mapper.setStatus(id,status,null);
        }else {
            this.mapper.setStatus(id,status,new Date());
        }
    }

    public AnnouncementVo buildVo(Announcement announcement) {
        AnnouncementVo announcementVo = new AnnouncementVo();
        announcementVoBuilder.buildVo(announcement, announcementVo);
        announcementVo.setStatusName(AnnouncementStatus.formValue(announcementVo.getStatus()).getLabel());
        announcementVo.setTypeName(AnnouncementType.formValue(announcementVo.getType()).getLabel());
        announcementVo.setUserName(userMapper.getNicknameById(announcementVo.getUserId()));
        return announcementVo;
    }

    public List<AnnouncementVo> getList(PageParam<Announcement> pageParam) {
        Page<Announcement> page = getPage(pageParam);
        if (page.getRecords().size() == 0) {
            return null;
        }
        List<Announcement> records = page.getRecords();
        List<AnnouncementVo> list = new ArrayList<>(records.size());
        for (Announcement record : records) {
            list.add(buildVo(record));
        }
        return list;
    }
}
